<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="5" :sm="24">
              <a-form-item label="">
                <a-select :allowClear="true" v-model="queryParam.village_id" placeholder="请选择村庄" default-value="0">
                  <a-select-option v-for="(item, index) in villList" :key="index" :value="item.village_id">
                    {{ item.village_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="">
                <a-select :allowClear="true" v-model="queryParam.status" placeholder="请选择状态" default-value="0">
                  <a-select-option value="1">整改中</a-select-option>
                  <a-select-option value="0">未整改</a-select-option>
                  <a-select-option value="2">已整改</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="">
                <a-input :allowClear="true" v-model="queryParam.family_no" placeholder="请输入家庭" />
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="">
                <a-input :allowClear="true" v-model="queryParam.fullname" placeholder="请输入志愿者姓名" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="">
                <a-input :allowClear="true" v-model="queryParam.address" placeholder="请输入定位信息"/>
              </a-form-item>
            </a-col>
            <a-col :md="23" :sm="24">
              <span class="table-page-search-submitButtons" style="float: right;">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" type="primary" @click="onExport">导出</a-button>
                <a-button style="margin-left: 8px" @click="()=> {queryParam = {}; $refs.table.refresh(true)}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="log_id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="id" slot-scope="text, r, index">
          {{ index + 1 }}
        </span>
        <span slot="status" slot-scope="text, record">
          <span v-if="record.status == 0">未整改</span>
          <span v-if="record.status == 1">整改中</span>
          <span v-if="record.status == 2">已整改</span>
        </span>
        <span style="text-align: center;" slot="action" slot-scope="text, record">
          <template>
            <a v-action:rectify @click="handleEdit(record, 0)">审核</a>
            <a-divider v-action:rectify_edit v-if="record.status == 0" type="vertical"/>
            <a v-action:rectify_edit v-if="record.status == 0" @click="handleEdit(record, 1)">编辑</a>
            <a-divider v-action:rectify_del v-if="record.status == 0" type="vertical"/>
            <a v-action:rectify_del v-if="record.status == 0" @click="handleRemove(record)">删除</a>
          </template>
        </span>
      </s-table>
      <!-- 增/查/改 弹出模板 -->
      <div v-if="visible">
        <create-form
          ref="createModal"
          :visible="visible"
          :loading="confirmLoading"
          :model="mdl"
          @cancel="handleCancel"
          @ok="handleOk"
          :okHidden="okHidden"
        />
      </div>
      <!-- 删除/停用确认窗 -->
      <a-modal
        title="提示"
        :visible="modal.show"
        :confirm-loading="modal.loading"
        @ok="modal.confirm"
        @cancel="modal.show = false"
      >
        <p>{{ modal.text }}</p>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { update, lists, listsFile, edit, changeStatus, del, rectifyInfo, actionaList } from '@/api/adjust'
import { villageList } from '@/api/distribution'
import CreateForm from './modules/CreateContentForm'

const columns = [
  {
    title: 'ID',
    dataIndex: 'log_id',
    align: 'center'
  },
  {
    title: '家庭户主',
    dataIndex: 'family_master_name',
    align: 'center'
  },
  {
    title: '家庭编号',
    dataIndex: 'family_no',
    align: 'center'
  },
  {
    title: '村庄',
    dataIndex: 'village_name',
    align: 'center'
  },
  {
    title: '定位信息',
    dataIndex: 'address',
    align: 'center'
  },
  {
    title: '积分类型',
    dataIndex: 'action_name',
    align: 'center'
  },
  {
    title: '分值',
    dataIndex: 'point',
    align: 'center'
  },
  {
    title: '操作者',
    dataIndex: 'fullname',
    align: 'center'
  },
  {
    title: '整改内容',
    dataIndex: 'action_content',
    align: 'center'
  },
  {
    title: '提交时间',
    dataIndex: 'created_at',
    align: 'center'
  },
  {
    title: '截止时间',
    dataIndex: 'expire_at',
    align: 'center'
  },
  {
    title: '整改时间',
    dataIndex: 'audit_at',
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    STable,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      okHidden: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        const params = {
          page: parameter.pageNo,
          per_page: parameter.pageSize
        }
        const res = await lists({
            ...params,
            ...this.queryParam
          })
        const result = {
          pageNo: res.current_page,
          totalPage: res.last_page,
          data: res.data,
          pageSize: 10,
          totalCount: res.total
        }
        return Promise.resolve(result)
      },
      modal: {
        show: false,
        text: '',
        loading: false,
        confirm: () => {},
        cancel: () => {}
      },
      selectedRowKeys: [],
      selectedRows: [],
      actiona_lists: [],
      villList: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  filters: {
  },
  created () {
    actionaList().then((res) => {
      // console.log(res)
      this.actiona_lists = res
    })
    villageList().then((res) => {
      this.villList = res.list
    })
  },
  methods: {
    onExport () {
      listsFile({ ...this.queryParam, export: 1 })
      .then((res) => {
        const blob = new Blob([ res ], { type: 'application/vnd.ms-excel;' })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        document.body.appendChild(downloadElement)
        downloadElement.click()
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
      })
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record, type) {
      rectifyInfo({ log_id: record.log_id }).then((res) => {
        const item = res
        if (item.action_image.indexOf(',') > -1) {
          item.action_image = item.action_image.split(',')
        } else {
          if (item.action_image) {
            item.action_image = [item.action_image]
          } else {
            item.action_image = []
          }
        }
        const actionImage = []
        for (let i = 0; i < item.action_image.length; i++) {
          actionImage[i] = {
            name: item.action_image[i],
            status: 'done',
            uid: 0,
            url: item.action_image[i]
          }
        }
        item.action_image = actionImage
        // console.log('图片数据', item.action_image)
        if (item.rectify_image.indexOf(',') > -1) {
          item.rectify_image = item.rectify_image.split(',')
        } else {
          if (item.rectify_image) {
            item.rectify_image = [item.rectify_image]
          } else {
            item.rectify_image = []
          }
        }
        item.villList = this.villList
        item.family_no = record.family_no
        item.type = type
        item.actiona_lists = this.actiona_lists
        this.mdl = item
        this.visible = true
        console.log('数据', item)
      })
    },
    handleOk (type, values, imgs) {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, ev) => {
        if (!errors) {
          const success = (res, info) => {
            if (res.is_ok == 'Y') {
              this.handleVisible()
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info(info)
            }
          }
          const final = () => { this.confirmLoading = false }
          if (type == 0) {
            edit(ev)
              .then(res => success(res, '审核成功'))
              .finally(final)
          } else {
            values.action_image = values.action_image.toString()
            update(values)
              .then(res => success(res, '编辑成功'))
              .finally(final)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleChangeStatus (record) {
      this.openModal(changeStatus, record, record.status == 1 ? '禁用' : '启用')
    },
    openModal (method, record, statusText) {
      this.modal = {
        ...this.modal,
        text: `确定${ statusText }该内容吗？`,
        show: true,
        confirm: async () => {
          try {
            this.modal.loading = true
            const res = await method({ log_id: record.log_id })
            if (res.is_ok == 'Y') {
              this.modal.loading = false
              this.modal.show = false
              this.$refs.table.refresh()
              this.$message.info(`${ statusText }成功`)
            }
          } catch (err) {
            console.warn(err)
            this.modal.loading = false
          }
        }
      }
    },
    handleCancel () {
      this.handleVisible()
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    async handleRemove (record) {
      this.openModal(del, record, '删除')
    },
    handleVisible () {
      this.visible = false
      setTimeout(() => {
        this.okHidden = false
      }, 350)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {}
    }
  }
}
</script>
